import React, { useEffect, useState } from 'react';
import { Link, useRoutes, useLocation, useNavigate } from 'react-router-dom';
import { routes } from './routes';

const App: React.FC = () => {
  const element = useRoutes(routes);
  const location = useLocation();
  const navigate = useNavigate();
  const [isTransitioning, setIsTransitioning] = useState(false);

  useEffect(() => {
    // 路由切换前的处理
    setIsTransitioning(true);
    
    // 模拟路由守卫，可以在这里添加权限验证等逻辑
    const checkRoutePermission = () => {
      // 这里可以添加实际的权限验证逻辑
      return true;
    };

    if (!checkRoutePermission()) {
      navigate('/');
      return;
    }

    // 路由切换动画结束后的处理
    const timer = setTimeout(() => {
      setIsTransitioning(false);
    }, 300);

    return () => clearTimeout(timer);
  }, [location, navigate]);

  return (
    <div style={{ padding: '20px' }}>
      <h1>React Router Demo</h1>
      <nav style={{
        padding: '1rem',
        backgroundColor: '#f0f0f0',
        marginBottom: '1rem',
        borderRadius: '8px',
        boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
      }}>
        <Link 
          to="/" 
          style={{
            color: location.pathname === '/' ? '#1890ff' : '#333',
            textDecoration: 'none',
            fontWeight: location.pathname === '/' ? 'bold' : 'normal',
            padding: '8px 16px',
            borderRadius: '4px',
            transition: 'all 0.3s ease',
            backgroundColor: location.pathname === '/' ? 'rgba(24,144,255,0.1)' : 'transparent'
          }}
        >首页</Link>
        <span style={{ margin: '0 10px', color: '#ccc' }}>|</span>
        <Link 
          to="/about"
          style={{
            color: location.pathname === '/about' ? '#1890ff' : '#333',
            textDecoration: 'none',
            fontWeight: location.pathname === '/about' ? 'bold' : 'normal',
            padding: '8px 16px',
            borderRadius: '4px',
            transition: 'all 0.3s ease',
            backgroundColor: location.pathname === '/about' ? 'rgba(24,144,255,0.1)' : 'transparent'
          }}
        >关于</Link>
      </nav>
      <div 
        style={{
          padding: '20px',
          backgroundColor: 'white',
          borderRadius: '8px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
          minHeight: '200px',
          opacity: isTransitioning ? 0 : 1,
          transform: `translateY(${isTransitioning ? '10px' : '0'})`,
          transition: 'all 0.3s ease'
        }}
        key={location.pathname}
      >
        {element}
      </div>
    </div>
  );
};

export default App;